<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    chartData:{
      type: Array,
      default(){
        return []
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions();
    },
    setOptions() {
      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c}次 (占比:{d}%)'
        },
        legend: {
          left: 'center',
          bottom: '5',
          itemGap: 15,
          formatter(value) {
            if(value.length > 12) return value.slice(0,12) + '...'
            return value
          }
        },
        color:['#5ab1ef', '#62d5b3', '#d4ec59', '#fb816d', '#45cfe5', '#e98bad', '#f4a8ab', '#b6a2de','#d15b7e','#f4516c'],
        series: [
          {
            type: 'pie',
            radius: '50%',
            center: ['50%', '34%'],
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{d}%'
            },
            data: this.chartData.map(item => {
              return {
                value: item.num,
                name: item.label
              }
            }),
            animationEasing: 'cubicInOut',
            animationDuration: 2600
          }
        ]
      })
    }
  }
}
</script>
